package com.zsk.gen;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class VelocityUtil {

    public static void build(String vmPath, String targetFilePath, VelocityContext context) {
        VelocityEngine ve = new VelocityEngine();
        // 输入编码
        ve.setProperty("input.encoding", "UTF-8");
        // 输出编码
        ve.setProperty("output.encoding", "UTF-8");
        // 设置从classPath下加载模板
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        // 进行初始化操作
        ve.init();
        // 加载模板，设定模板编码
        Template t = ve.getTemplate(vmPath, "utf-8");
        // 设置输出
        PrintWriter writer = null;
        try {
            File file = new File(targetFilePath);
            if (!file.getParentFile().isDirectory()) {
                file.getParentFile().mkdirs();
            }
            writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(targetFilePath), "UTF-8"));
            // 将环境数据转化输出
            t.merge(context, writer);
        } catch (Exception e) {
            log.error(e.toString());
        } finally {
            writer.close();
        }
    }

    /**
     * 创建上下文
     * 
     * @return
     */
    public static VelocityContext createContext() {
        return new VelocityContext();
    }

}
